import subprocess
import sys
import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
import time
import threading

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def stop_process_on_port(port):
    """停止指定端口上的进程"""
    try:
        result = subprocess.run(['netstat', '-ano'], capture_output=True, text=True)
        for line in result.stdout.splitlines():
            if f":{port}" in line:
                pid = line.split()[-1]
                print(f"找到绑定在端口 {port} 上的进程，PID: {pid}")

                subprocess.run(['taskkill', '/F', '/PID', pid], check=True)
                print(f"成功终止 PID: {pid} 的进程")
                return {"success": True, "message": f"成功终止 PID {pid} 的进程"}

        return {"success": False, "message": f"没有找到占用端口 {port} 的进程"}
    except Exception as e:
        return {"success": False, "message": f"发生错误: {str(e)}"}

def monitor_port(port, timeout=10):
    """循环监控指定端口是否有进程在监听，加入超时机制"""
    start_time = time.time()
    while True:
        result = subprocess.run(['netstat', '-ano'], capture_output=True, text=True)
        for line in result.stdout.splitlines():
            if f":{port}" in line:
                pid = line.split()[-1]
                print(f"端口 {port} 正在被 PID {pid} 占用")
                return {"success": True, "message": f"找到进程 PID {pid} 监听端口 {port}"}

        if time.time() - start_time > timeout:
            return {"success": False, "message": f"超时未找到进程监听端口 {port}"}

        time.sleep(1)

def start_uvicorn():
    """启动 Uvicorn 服务器"""
    # subprocess.run([sys.executable, '-m', 'uvicorn', 'main:app', '--host', '192.168.1.8', '--port', '8088'])
    subprocess.run([sys.executable, '-m', 'uvicorn', 'main:app', '--host', '192.168.31.107', '--port', '8088'])

@app.post("/restart-server")
async def restart_server():
    # 步骤1: 停止占用端口的进程
    stop_response = stop_process_on_port(8088)

    if stop_response["success"]:
        # 步骤2: 启动 uvicorn 服务器（异步执行）
        threading.Thread(target=start_uvicorn, daemon=True).start()

        # 步骤3: 等待端口监听成功
        port_monitor_response = monitor_port(8088)
        if port_monitor_response["success"]:
            return {"success": True, "message": "服务器已成功重启并监听端口 8088"}
        else:
            return {"success": False, "message": port_monitor_response["message"]}

    return stop_response  # 如果停止进程失败，返回失败信息

if __name__ == "__main__":
    # uvicorn.run(app, host="192.168.1.8", port=1111)
    uvicorn.run(app, host="192.168.31.107", port=1111)
